package com.mall.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mall.bean.Cart;
import com.mall.bean.User;
import com.mall.service.ICartService;

@Controller
public class CartController {

	@Resource
	private ICartService cartService;

	//加入购物车
	@RequestMapping("addCart")
	@ResponseBody
	public Map<String, Object> addCart(@Param("requestName") String requestName, @Param("goods_id") Integer goods_id, Cart cart, HttpSession session, HttpServletResponse response) throws Exception {

		Map<String, Object> resMap = new HashMap<String, Object>();

		System.out.println("goods_id：" + goods_id);

		User user = (User) session.getAttribute("user");
		cart.setGoods_id(goods_id);
		cart.setUser_id(user.getUser_id());
		//图书
		if ("goods".equals(requestName)) {
			if (cartService.isExistGoods(cart)) {
				resMap.put("exist", "请勿重新加购");
			} else {
				cartService.addCart(cart);
				resMap.put("success", "您已加入成功");
			}
		}
		return resMap;
	}

	//查询并展示购物车
	@RequestMapping("shopping-cart")
	public String myCart(User user, Model model, HttpSession session) {
		System.out.println("开始执行");
		User user1 = cartService.myCart(user);
		System.out.println("购物车：" + user1);
		model.addAttribute("user", user1);

		return "shopping-cart";
	}

	//删除购物车商品
	@RequestMapping("delCartGoods")
	@ResponseBody
	public Map<String, Object> delCartGoods(@Param("goods_id") Integer goods_id, Cart cart, HttpSession session) {

		Map<String, Object> resMap = new HashMap<String, Object>();
		cart.setGoods_id(goods_id);
		cartService.delCartGoods(cart);
		User user = (User) session.getAttribute("user");
		User user1 = cartService.myCart(user);
		resMap.put("user", user1);
		return resMap;
	}
}
